package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.User;
import service.UserService;
import util.Page;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("/index")
    public String index(){
        //逻辑视图名
        return "/index";
    }

    //在方法上写参数就可以接收到参数
    @RequestMapping("/login")
    public String login(User user){
        boolean flag = userService.login(user);
        if (flag){
            // /WEB-INF/user/list.jsp
            return "index";
        }else {
            //登录逻辑
            return "login";
        }
    }

    //全查询
    @RequestMapping("/list/{currentPage}")
    public String list(User user, @PathVariable("currentPage") Integer currentPage, Model model){
        //查询数据
        Page page=new Page();
        int totalcount=userService.count(user);
        page.setCurrentPage(currentPage);
        page.setTotalCount(totalcount);
        page.setTotalPage();

        //计算偏移量
        int offset=page.getPageSize()*(currentPage-1);
        List<User> users=userService.findAll(user,offset,page.getPageSize());

        //数据返回
        model.addAttribute("users",users);
        model.addAttribute("page",page);
        model.addAttribute("user",user);

        return "user/list";
    }
    //跳转新增
    @RequestMapping("/toadd")
    public String toadd(){
        return "user/add";
    }
    //保存新增
    @RequestMapping("/addSave")
    public String addSave(User user){
        int result=userService.addUser(user);
        if (result > 0) {
            return "redirect:/user/list/1";
        }else {
            return "user/add";
        }
    }
    //删除
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable("id")Integer id){
        int result= userService.deleteUserById(id);
        return result>0?"redirect:/user/list/1":"error";
    }
    @RequestMapping("/toupdate/{id}")
    public String toupdate(@PathVariable("id") Integer id,Model model){
        User user=userService.findById(id);
        model.addAttribute("user",user);
        return "user/update";
    }
    @RequestMapping("/updateSave")
    public String updateSave(User user){
        int result=userService.updateUser(user);
        return result>0?"redirect:/user/list/1":"error";
    }
}